//
//  GYShopingCartViewController.m
//  GoodLuck
//
//  Created by apple on 2018/3/27.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYShopingCartViewController.h"
#import "GYBasePopoverViewController.h"
#import "PopoverAnimation.h"
#import "GYSearchViewController.h"
#import "GYSystemMessageViewController.h"
#import "GYUser.h"
#import "GYNoAddressView.h"
#import "GYNetWorkTools.h"
#import "GYShopingCart.h"
#import "GYShopingCartGoodsTableViewCell.h"
#import "GYShopingCartHeadView.h"
#import "GYShopingCart.h"
#import "GYShopingCartGoods.h"
#import "GYConfirmOrderViewController.h" 

@interface GYShopingCartViewController ()<UITableViewDelegate,UITableViewDataSource>

/** 动画代理 */
@property (nonatomic, strong) PopoverAnimation *animationDelegate;

/** 购物车为空的时候的视图 */
@property (nonatomic, strong) GYNoAddressView *noShopingCartGoodsView;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *payBtuState;
@property (weak, nonatomic) IBOutlet UIButton *confirmBtu;

/** 数据源 */
@property (nonatomic, strong) NSArray *shopingCartList;

/** 要购物商品的数组 */
@property (nonatomic, strong) NSMutableArray *purchaseGoodsList;

//总价格
@property (weak, nonatomic) IBOutlet UILabel *goodsSumPriceLable;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *payViewBottomMarginCons;

@end

@implementation GYShopingCartViewController

//付款按钮的选中状态
- (IBAction)payBtuClick:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    if (sender.isSelected) {
        self.confirmBtu.backgroundColor = RGBColor(15, 206, 194);
        self.confirmBtu.enabled = YES;
    }else {
        self.confirmBtu.backgroundColor = [UIColor darkGrayColor];
        self.confirmBtu.enabled = NO;
    }
}

//确认订单信息
- (IBAction)confirmOrderInfoBtuClick:(UIButton *)sender {
    
    GYConfirmOrderViewController *confirmOrderVC = [[GYConfirmOrderViewController alloc] init];
    confirmOrderVC.directBuy = NO;
    confirmOrderVC.shopingCartList = self.shopingCartList;
    [self.navigationController pushViewController:confirmOrderVC animated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.payViewBottomMarginCons.constant = iPhoneX ? 44 : 0;
    //初始化
    [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //加载购物车数据
    [self loadShopingCartList];
}

- (void)setupUI {
    self.navigationItem.title = @"购物车";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"more_b" tagret:self action:@selector(moreBtuClick) button:nil];
    
    //设置表格的一些属性
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, CGFLOAT_MIN)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, CGFLOAT_MIN)];
}

- (void)moreBtuClick {
    GYBasePopoverViewController *basePopoverVC = [[GYBasePopoverViewController alloc] initWithNibName:@"GYBasePopoverViewController" bundle:nil];
    __weak typeof(self) weakSelf = self;
    basePopoverVC.popoverViewSelectIndexCallBack = ^(NSInteger index) {
        switch (index) {
            case 0:
            {
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
                break;
                
            case 1:
            {
                GYSearchViewController *searchVC = [[GYSearchViewController alloc] init];
                [self.navigationController pushViewController:searchVC animated:YES];
            }
                break;
                
            case 2:
            {
                weakSelf.tabBarController.selectedIndex = 2;
            }
                break;
                
            case 3:
            {
                GYSystemMessageViewController *systemMessageVC = [[GYSystemMessageViewController alloc] initWithNibName:@"GYSystemMessageViewController" bundle:nil];
                [weakSelf.navigationController pushViewController:systemMessageVC animated:YES];
                
            }
                break;
                
            default:
                break;
        }
    };
    basePopoverVC.titles = @[@"首页",@"搜索",@"我的商城",@"消息"];
    basePopoverVC.images = @[@"home_w",@"search_w",@"ff_icon4",@"message_w"];
    
    self.animationDelegate = [[PopoverAnimation alloc] init];
    self.animationDelegate.popoverFrame = CGRectMake(ScreenWidth-widthScale(130, iphone6_W)-5, 50, widthScale(130, iphone6_W), basePopoverVC.titles.count*50);
    basePopoverVC.transitioningDelegate = (id)weakSelf.animationDelegate;
    
    basePopoverVC.modalPresentationStyle = UIModalPresentationCustom;
    [self presentViewController:basePopoverVC animated:YES completion:nil];
}

- (void)loadShopingCartList {
    [EasyLodingView showLodingText:@"正在加载..." config:^EasyLodingConfig *{
        EasyLodingConfig *config = [EasyLodingConfig shared];
        config.showOnWindow = YES;
        
        return config;
    }];
    [GYNetWorkTools requestShopingCartList:^(NSDictionary *obj) {
        //NSLog(@"obj========%@",obj);
        int code = [[obj objectForKey:@"code"] intValue];
        NSDictionary *datas = [obj objectForKey:@"datas"];
        if (code == 200) {
            [EasyLodingView hidenLoingInView:[UIApplication sharedApplication].keyWindow];
            NSArray *cart_list = [datas objectForKey:@"cart_list"];
            if (cart_list.count == 0) {
                if (self.noShopingCartGoodsView == nil) {
                    [self getNoShopingCartGoodsView];
                }else {
                    self.noShopingCartGoodsView.hidden = NO;;
                }
            }else {
                self.noShopingCartGoodsView.hidden = YES;
                self.shopingCartList = [GYShopingCart jsonShopintCartList:cart_list];
                
                //这里要赋值所有商品总价
                self.goodsSumPriceLable.text = [NSString stringWithFormat:@"¥%0.2f",[[datas objectForKey:@"sum"] floatValue]];
                
                [self.tableView reloadData];
            }
        }else if (code == 400) {
            [EasyLodingView hidenLoingInView:[UIApplication sharedApplication].keyWindow];
            [EasyTextView showText:@"加载数据出错!"];
        }
    } error:^(NSError *error) {
        [EasyLodingView hidenLoingInView:[UIApplication sharedApplication].keyWindow];
        [EasyTextView showText:@"加载数据出错!"];
        NSLog(@"ShopingCartListFailed=====%@",error);
    }];
}

#pragma mark -- UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.shopingCartList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[self.shopingCartList[section] goods] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GYShopingCartGoodsTableViewCell *cell = [GYShopingCartGoodsTableViewCell cellWithTableView:tableView];
    GYShopingCartGoods *goods = [self.shopingCartList[indexPath.section] goods][indexPath.row];
    cell.goods = goods;
    __weak typeof(self) weakSelf = self;
    cell.deleteOrAddGoodsNumCallBack = ^(NSInteger goodsNum) {
        [weakSelf loadShopingCartList];
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    GYShopingCartGoodsTableViewCell *cell = [GYShopingCartGoodsTableViewCell cellWithTableView:tableView];
    
    return [cell getHeight:[self.shopingCartList[indexPath.section] goods][indexPath.row]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //1.改变当前cell的选中状态
        NSArray *goods = [self.shopingCartList[indexPath.section] goods];
        GYShopingCartGoods *good = goods[indexPath.row];
        good.selectState = !good.isSelectState;
        
        //2.修改店铺的选中状态
        BOOL isSelect = NO;
        for (GYShopingCartGoods *model in goods) {
            if (model.isSelectState == NO) {
                isSelect = YES;
                break;
            }
        }
        GYShopingCart *cart = self.shopingCartList[indexPath.section];
        cart.selectState = !isSelect;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //3.刷新表格
            [tableView reloadData];
            [self updateGoodsSumPrice];
        });
        
    });
    
    
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    GYShopingCartHeadView *headView = [GYShopingCartHeadView headViewWithTbaleView:tableView];
    headView.frame = CGRectMake(0, 0, ScreenWidth, 50);
    GYShopingCart *cart = self.shopingCartList[section];
    headView.model = cart;
    headView.updateSelectStateCallBack = ^{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            cart.selectState = !cart.isSelectState;
            for (GYShopingCartGoods *model in cart.goods) {
                model.selectState = cart.isSelectState;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [tableView reloadData];
                [self updateGoodsSumPrice];
            });
        });
    };
    
    return headView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *bgview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
    bgview.backgroundColor = [UIColor clearColor];
    
    return bgview;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}


/**
 更新商品总价格
 */
- (void)updateGoodsSumPrice {
    float supPrice = 0.0;
    for (GYShopingCart *model in self.shopingCartList) {
        for (GYShopingCartGoods *goods in model.goods) {
            if (goods.isSelectState) {
                supPrice += [goods.goods_price floatValue] * [goods.goods_num intValue];
            }
        }
    }
    self.goodsSumPriceLable.text = [NSString stringWithFormat:@"%0.2f",supPrice];
}

#pragma mark -- 创建视图

- (void)getNoShopingCartGoodsView {
    GYNoAddressView *noShopingCartGoodsView = [[[NSBundle mainBundle] loadNibNamed:@"GYNoAddressView" owner:nil options:nil] firstObject];
    noShopingCartGoodsView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight-64);
    noShopingCartGoodsView.markImageView.image = [UIImage imageNamed:@"ff_icon3"];
    noShopingCartGoodsView.headLable.text = @"您的购物车还是空的";
    noShopingCartGoodsView.footLable.text = @"去挑一些中意的商品吧";
    [noShopingCartGoodsView.addBtu setTitle:@"随便逛逛" forState:UIControlStateNormal];
    __weak typeof(self) weakSelf = self;
    noShopingCartGoodsView.addNewAddressCallBack = ^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    [self.view addSubview:noShopingCartGoodsView];
    
    self.noShopingCartGoodsView = noShopingCartGoodsView;
}

#pragma mark -- 懒加载

- (NSMutableArray *)purchaseGoodsList {
    if (!_purchaseGoodsList) {
        _purchaseGoodsList = [NSMutableArray array];
    }
    return _purchaseGoodsList;
}





















@end
